<template>
  <el-dialog v-model="dialogVisible" title="项目进度" :close-on-click-modal="false" width="80%">
    <div>
      <div class="flex-input">
        <div>
          <el-input v-model="projectName" placeholder="项目名称" />
        </div>
        <div>
          <el-input v-model="chargerName" placeholder="负责人" />
        </div>
        <div style="display:flex; width: 400px">
          <div>
            <el-input v-model="minfee" placeholder="请输入最小总经费" @input="filterNonNumeric(minfee)" />
          </div>
          <div style="line-height: 30px">
            至
          </div>

          <div>
            <el-input v-model="maxfee" placeholder="请输入最大总经费" @input="filterNonNumeric(maxfee)" />
          </div>

          <!--          <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>-->
        </div>
        <div>
          <el-button type="primary" icon="Search" @click="confirmClick">查询</el-button>
          <el-button @click="download"><svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出</el-button>

        </div>
      </div>
      <div>
        <el-table border style="width: 100%" :data="tableData" @sort-change="handleSortChange">
          <el-table-column prop="projectName" label="项目名称" sortable="p.name"></el-table-column>
          <el-table-column prop="chargerName" label="负责人" sortable="p.charger_name"></el-table-column>
          <el-table-column prop="beginDate" label="开始时间" sortable="p.BEGIN_DATE"></el-table-column>
          <el-table-column prop="feeAuthorize" label="项目总经费(元)" sortable="p.fee_authorize"></el-table-column>
          <el-table-column prop="incomeFee" label="到账金额(元)" ></el-table-column>
          <el-table-column prop="payoutFee" label="支出金额(元)" ></el-table-column>
          <el-table-column label="到账率" >
            <template #default="{ row }">
              <el-progress
                :percentage="row.incomeRate!== null? parseFloat(row.incomeRate.replace('%', '')) : 0"></el-progress>
            </template>
          </el-table-column>
          <el-table-column label="执行率" >
            <template #default="{ row }">
              <el-progress
                :percentage="row.executeRate!== null? parseFloat(row.executeRate.replace('%', '')) : 0"></el-progress>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
             <el-button plain type="primary" size="small" @click="handlekmjd(scope.row)">科目进度</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="example-pagination-block">
          <el-pagination layout="->,prev, pager, next, total" :total="count" currentPage1="10"
            @current-change="handleCurrentChange" />
        </div>
      </div>



    </div>
  </el-dialog>
  <zxjdDialogkmjd ref="Dialogkmjd"></zxjdDialogkmjd>

</template>

<script setup lang="ts">
import { ref } from 'vue';
import {
  projectlist,exportpro
} from '../../../api/money/zxjdApi'
import {handleFileDownload} from './../../../utils/downloadSz'
import zxjdDialogkmjd from './zxjdDialogKMJD.vue'
import {ElMessage} from "element-plus";
//排序
const orderByColumn =ref("p.NAME");
const isAsc = ref("descending");
//分页
const handleCurrentChange = (val: string) => {
  projectlist({
    projectName:projectName.value,
    chargerName:chargerName.value,
    params:{
      minfee:minfee.value,
      maxfee:maxfee.value,
    },
    pageNum:val,
    pageSize:10,
    orderByColumn:orderByColumn.value,
    isAsc:isAsc.value,
    ...rows.value
  }).then((res)=>{
    count.value = res.total
    tableData.value = res.rows

  })
  console.log(`current page: ${val}`)
}


const projectName  = ref(null);//项目名称
const chargerName = ref(null);//负责人
const minfee = ref('');
const maxfee = ref('');
const errorMessage = ref('');
//验证最大最小
const filterNonNumeric = (valueRef) => {
  valueRef.value = valueRef.value.replace(/[^\d]/g, '');
};
const validateFunds = () => {
  // 检查最小经费是否为有效数字，若不是则置为空
  console.log(minfee.value)
  if (minfee.value!== '' && isNaN(parseFloat(minfee.value))) {
    errorMessage.value = '最小总经费必须为数字';
    minfee.value = null;
    ElMessage({ message: '最小总经费必须为数字', type: 'error' });
    return false;
  }

  // 检查最大经费是否为有效数字，若不是则置为空
  console.log(maxfee.value)
  if (maxfee.value!== '' && isNaN(parseFloat(maxfee.value))) {
    errorMessage.value = '最大总经费必须为数字';
    maxfee.value = null;
    ElMessage({ message: '最大总经费必须为数字', type: 'error' });
    return false;
  }

  // 将输入转换为数字类型
  const minFeeNum = parseFloat(minfee.value);
  const maxFeeNum = parseFloat(maxfee.value);

  if (!isNaN(minFeeNum) && !isNaN(maxFeeNum) && minFeeNum > maxFeeNum) {
    errorMessage.value = '最小总经费不能大于最大总经费';
    minfee.value = null;
    maxfee.value = null;
    ElMessage({ message: '最小总经费不能大于最大总经费', type: 'error' });
    return false;
  }

  errorMessage.value = '';
};
const confirmClick = () => {
  if(validateFunds() == false){
    return
  }
  console.log(validateFunds())
  console.log({...rows.value})
  projectlist({
    projectName:projectName.value,
    chargerName:chargerName.value,
    params:{
      minfee:minfee.value,
      maxfee:maxfee.value,
    },
    pageNum:1,
    pageSize:10,
    orderByColumn:orderByColumn.value,
    isAsc:isAsc.value,
    ...rows.value
  }).then((res)=>{
    count.value = res.total
    tableData.value = res.rows

  })
}
const Dialogkmjd = ref(null)
const handlekmjd = (row) => {
  Dialogkmjd.value.openDialogKMJD(row)
}



const dialogVisible = ref(false)

const count = ref(0)

//openDialogxyjd
const rows = ref()
//请求列表
const openDialogxmjd = function (row) {

  rows.value = row
  dialogVisible.value = true
  projectName.value =''
  chargerName.value =''
  minfee.value =''
  maxfee.value =''
  console.log(row) //有数据
  console.log(row.value) //没有数据undf
  // 复制一份 getListParme 对象，避免修改原始数据
  const requestData = { ...row };
  // 将 unitld 从数组转换为字符串
  if (Array.isArray(requestData.projectTypeCode)) {
    // requestData.projectTypeCode = requestData.projectTypeCode.join(',');//项目分类
    // requestData.executeYear = requestData.executeYear.join(',');//执行周期
  }
  console.log(requestData)
  projectlist({
    pageNum:1,
    pageSize:10,
    orderByColumn:orderByColumn.value,
    isAsc:isAsc.value,
    ...row
  }).then((res)=>{
    count.value = res.total
    tableData.value = res.rows

  })

}

const download = () => {

  exportpro({
    projectName:projectName.value,
        chargerName:chargerName.value,
      params:{
    minfee:minfee.value,
        maxfee:maxfee.value,
  },
  ...rows.value
  })
      .then((res)=>{
        if (!(res instanceof Blob)) {
          ElMessage({
            type: 'info',
            message: '响应数据不是 Blob 类型',
          })
        }else {
          handleFileDownload(res, '项目进度');
        }
      })
}

// 初始表格数据
const tableData = ref([
//   authorizeDate: "2025"//立项年度
// beginDate: null
// chargerName: null
// executeRate: "0.00000088028169"//执行率
// executeYear: null //执行周期
// feeAuthorize: null
// incomeFee: null
// incomeRate: "24.4718309859" //到账率
// payoutFee: null
// projectId: null
// projectName: null
// projectTypeCode: "Z07"
// projectTypeCodeName: "国家自然科学基金"//项目分类
// unitId: null
// unitName: null
//   {
//     id: 1,
//     projectTypeCodeName: '科研项目',
//     authorizeDate: '2025',
//     executeYear: '2025 - 2026',
//     incomeRate: '80%',
//     executeRate: '70%',
//     hasChildren: true
//   },
//   {
//     id: 2,
//     projectTypeCodeName: '教学项目',
//     authorizeDate: '2024',
//     executeYear: '2024 - 2025',
//     incomeRate: '90%',
//     executeRate: '85%',
//     hasChildren: false
//   }
]);



// 处理排序变化的函数
// prop：表示当前进行排序的列对应的字段名
// order：表示当前的排序顺序，有三种可能的值：
// 'ascending'：代表正序排序。
// 'descending'：代表倒序排序。
// null：表示取消排序，在当前代码中暂未对该情况进行处理。
const handleSortChange = (row) => {
  orderByColumn.value = row.column.sortable;
  isAsc.value=row.order;
  confirmClick();
};

defineExpose({
  openDialogxmjd,
});
</script>

<style scoped>
.flex-input{
  display: flex;
  margin-right: 10px;
  margin-bottom: 10px;
}
.flex-input > div{
  margin-right: 10px;
  width: 20%;
}
</style>